package com.ins1st.config.shiro;

import com.alibaba.fastjson.JSON;
import com.ins1st.base.R;
import com.ins1st.util.ShiroUtil;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @program: ins1st-cloud
 * @description:
 * @author: coderSun
 * @create: 2019-11-19 16:19
 **/
public class LoginFormFilter extends AccessControlFilter {

    private static final Logger log = LoggerFactory.getLogger(LoginFormFilter.class);

    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        if (isLoginRequest(request, response)) {
            return true;
        } else {
            Subject subject = getSubject(request, response);
            return subject.getPrincipal() != null;
        }
    }

    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        HttpServletRequest httpServletRequest = WebUtils.toHttp(servletRequest);
        HttpServletResponse httpServletResponse = WebUtils.toHttp(servletResponse);

        /**
         * 如果是ajax请求则不进行跳转
         */
        if (httpServletRequest.getHeader("x-requested-with") != null
                && httpServletRequest.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
            httpServletResponse.setHeader("sessionstatus", "timeout");
            return false;
        } else {

            /**
             * 第一次点击页面
             */
            String referer = httpServletRequest.getHeader("Referer");
            if (referer == null) {
                saveRequestAndRedirectToLogin(httpServletRequest, httpServletResponse);
                return false;
            } else {

                /**
                 * 从别的页面跳转过来的
                 */
                if (ShiroUtil.getSubject().getSession().getAttribute("sessionFlag") == null) {
                    httpServletRequest.getRequestDispatcher("/login").forward(servletRequest, servletResponse);
                    return false;
                } else {
                    saveRequestAndRedirectToLogin(servletRequest, servletResponse);
                    return false;
                }
            }
        }
    }

    /**
     * 向response写数据
     *
     * @param response
     * @param r
     */
    protected void writeJson(HttpServletResponse response, R r) {
        try {
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().write(JSON.toJSONString(r));
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 判断属于什么请求
     *
     * @param request
     * @return
     */
    private boolean isAjax(HttpServletRequest request) {
        return (request.getHeader("X-Requested-With") != null
                && "XMLHttpRequest".equals(request.getHeader("X-Requested-With").toString()));
    }
}
